<template>
  <div class="min-h-screen bg-gray-50 dark:bg-gray-900 py-8">
    <div class="max-w-7xl mx-auto px-4">
      <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-900 dark:text-white mb-2">我的收藏</h1>
        <p class="text-gray-600 dark:text-gray-400">共收藏 {{ favorites.length }} 个工具</p>
      </div>

      <div v-if="loading" class="text-center py-12">
        <Icon name="line-md:loading-loop" class="w-12 h-12 text-blue-600 mx-auto" />
        <p class="mt-4 text-gray-600 dark:text-gray-400">加载中...</p>
      </div>

      <div v-else-if="favorites.length === 0" class="text-center py-20">
        <Icon name="heroicons:heart" class="w-24 h-24 text-gray-400 mx-auto mb-4" />
        <h3 class="text-xl font-semibold text-gray-900 dark:text-white mb-2">还没有收藏</h3>
        <p class="text-gray-600 dark:text-gray-400 mb-6">快去发现喜欢的开发工具吧！</p>
        <NuxtLink to="/tools" class="btn btn-primary">
          去发现工具
        </NuxtLink>
      </div>

      <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <ToolCard
          v-for="favorite in favorites"
          :key="favorite.id"
          :tool="favorite.tool"
          @favorite-changed="handleFavoriteChanged"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

definePageMeta({
  middleware: 'auth'
})

const $api = useNuxtApp().$api
const toast = useToast()

const favorites = ref<any[]>([])
const loading = ref(true)

onMounted(async () => {
  await loadFavorites()
})

const loadFavorites = async () => {
  loading.value = true
  try {
    favorites.value = await $api('/favorites') as any[]
  } catch (error) {
    console.error('加载收藏失败:', error)
    toast.error('加载收藏失败')
  } finally {
    loading.value = false
  }
}

const handleFavoriteChanged = (toolId: number, isFavorited: boolean) => {
  if (!isFavorited) {
    // 从列表中移除
    favorites.value = favorites.value.filter(f => f.tool.id !== toolId)
  }
}

// SEO
useHead({
  title: '我的收藏 - DevToolsHub',
  meta: [
    { name: 'description', content: '查看我收藏的开发工具' },
    { name: 'robots', content: 'noindex, nofollow' }
  ]
})
</script>

